﻿using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using RotovapPlatform.UI.ViewModels.DeviceMaintenance.ManualOperation;
using System.Windows.Input;
using System;
using Microsoft.Extensions.Logging;

namespace RotovapPlatform.UI.Views.DeviceMaintenance.ManualOperation
{
	public partial class MotorControlView : UserControl
	{
		private MotorControlViewModel _viewModel;
		private ILogger<MotorControlView> _logger;

		public MotorControlView()
		{
			InitializeComponent();

			// 获取ViewModel和Logger
			_viewModel = App.ServiceProvider.GetRequiredService<MotorControlViewModel>();
			_logger = App.ServiceProvider.GetRequiredService<ILogger<MotorControlView>>();
			DataContext = _viewModel;

			// 注册事件
			Loaded += MotorControlView_Loaded;
			Unloaded += MotorControlView_Unloaded;
		}

		private void MotorControlView_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			try
			{
				_logger?.LogInformation("MotorControlView页面已加载");

				// 重新初始化ViewModel
				_viewModel.Reinitialize();
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "MotorControlView加载异常");
			}
		}

		private void MotorControlView_Unloaded(object sender, System.Windows.RoutedEventArgs e)
		{
			try
			{
				_logger?.LogInformation("MotorControlView页面已卸载");

				// 在页面卸载时释放ViewModel资源
				if (_viewModel is IDisposable disposable)
				{
					disposable.Dispose();
					_logger?.LogInformation("MotorControlViewModel已释放");
				}
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "MotorControlView卸载异常");
			}
		}

		private void JogPlus_MouseDown(object sender, MouseButtonEventArgs e)
		{
			if (DataContext is MotorControlViewModel viewModel)
			{
				viewModel.StartJogPlus();
			}
		}

		private void JogMinus_MouseDown(object sender, MouseButtonEventArgs e)
		{
			if (DataContext is MotorControlViewModel viewModel)
			{
				viewModel.StartJogMinus();
			}
		}

		private void Jog_MouseUp(object sender, MouseEventArgs e)
		{
			if (DataContext is MotorControlViewModel viewModel)
			{
				viewModel.StopJog();
			}
		}

		private void Jog_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
		{
			if (DataContext is MotorControlViewModel viewModel)
			{
				viewModel.StopJog();
			}
		}
	}
}